<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2 class="page-title gradient-text">👥 用户管理</h2>
          <p class="page-subtitle">管理系统中的所有用户，包括查看、编辑、禁用用户以及管理用户属性</p>
        </div>
        <div class="header-right">
          <div class="user-stats">
            <div class="stat-item">
              <span class="stat-label">总用户数</span>
              <span class="stat-value">{{ total }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">活跃用户</span>
              <span class="stat-value success">{{ activeUsersCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section tech-card">
      <div class="card-glow"></div>
      <div class="search-header">
        <h3 class="search-title">🔍 用户筛选</h3>
        <div class="search-stats">
          <span class="result-count">共找到 {{ total }} 个用户</span>
        </div>
      </div>
      
      <div class="search-form">
        <el-form :model="searchForm" class="tech-form">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="搜索关键词">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="输入昵称或手机号搜索"
                  clearable
                  class="tech-input"
                  @keyup.enter="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            
            <el-col :span="6">
              <el-form-item label="用户状态">
                <el-select 
                  v-model="searchForm.is_active" 
                  placeholder="选择状态" 
                  clearable 
                  class="tech-select"
                >
                  <el-option label="活跃" :value="true">
                    <span style="display: flex; align-items: center; gap: 8px;">
                      <span class="status-dot status-success"></span>
                      <span>活跃</span>
                    </span>
                  </el-option>
                  <el-option label="禁用" :value="false">
                    <span style="display: flex; align-items: center; gap: 8px;">
                      <span class="status-dot status-danger"></span>
                      <span>禁用</span>
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :span="10">
              <el-form-item class="search-actions">
                <el-button class="tech-btn primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button class="tech-btn outline" @click="handleReset">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
                <el-button class="tech-btn success" @click="handleExport">
                  <el-icon><Download /></el-icon>
                  导出
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="table-section tech-card">
      <div class="card-glow"></div>
      <div class="table-header">
        <h3 class="table-title">👤 用户列表</h3>
        <div class="table-actions">
          <el-button class="tech-btn outline" @click="fetchUsers">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button class="tech-btn danger" @click="deleteNoAvatarUsers" :loading="isDeletingNoAvatarUsers">
            删除无头像用户
          </el-button>
        </div>
      </div>

      <div class="table-container tech-table">
        <el-table
          v-loading="loading"
          :data="userList"
          loading-text="数据加载中..."
          element-loading-background="rgba(0, 0, 0, 0.8)"
          element-loading-text="正在获取用户数据..."
          element-loading-spinner="tech-loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          
          <el-table-column prop="id" label="ID" width="80">
            <template #default="{ row }">
              <div class="user-id">
                <span class="id-badge">#{{ row.id }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="用户信息" min-width="200">
            <template #default="{ row }">
              <div class="user-info">
                <el-avatar :src="getAvatarUrl(row.avatar_url)" :size="40" class="user-avatar">
                  <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                </el-avatar>
                <div class="user-details">
                  <div class="user-name">{{ row.nickname || '未设置昵称' }}</div>
                  <div class="user-phone">{{ row.phone || '未绑定手机' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="性别" width="80">
            <template #default="{ row }">
              <div class="gender-tag">
                <span v-if="row.gender === 1" class="gender-icon male">♂</span>
                <span v-else-if="row.gender === 2" class="gender-icon female">♀</span>
                <span v-else class="gender-icon unknown">?</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <div class="status-switch">
                <el-switch
                  v-model="row.is_active"
                  @change="handleStatusChange(row)"
                  :loading="row.statusLoading"
                  :active-color="'var(--accent-green)'"
                  :inactive-color="'var(--text-muted)'"
                />
                <span class="status-label">{{ row.is_active ? '活跃' : '禁用' }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="orders_count" label="订单数" width="100">
            <template #default="{ row }">
              <div class="orders-count">
                <el-icon class="order-icon"><ShoppingCart /></el-icon>
                <span class="count">{{ row.orders_count || 0 }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="created_at" label="注册时间" width="160">
            <template #default="{ row }">
              <div class="time-info">
                <el-icon class="time-icon"><Clock /></el-icon>
                <span>{{ formatTime(row.created_at) }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button class="tech-btn primary" size="small" @click="handleView(row)">
                                     <el-icon><ViewIcon /></el-icon>
                  查看
                </el-button>
                <el-button class="tech-btn warning" size="small" @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-dropdown 
                  @command="handleCommand($event, row)"
                  trigger="click"
                  class="action-dropdown"
                >
                  <el-button class="tech-btn outline" size="small">
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu class="tech-dropdown">
                      <el-dropdown-item command="attributes">
                        <el-icon><Setting /></el-icon>
                        <span>管理属性</span>
                      </el-dropdown-item>
                      <el-dropdown-item command="relations">
                        <el-icon><Connection /></el-icon>
                        <span>关系管理</span>
                      </el-dropdown-item>
                      <el-dropdown-item command="disable" divided>
                        <el-icon><Close v-if="row.is_active" /><Check v-else /></el-icon>
                        <span>{{ row.is_active ? '禁用用户' : '启用用户' }}</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section tech-pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 用户详情对话框 -->
    <UserDetailDialog
      v-model="detailDialogVisible"
      :user-id="selectedUserId"
      @updated="fetchUsers"
    />

    <!-- 用户编辑对话框 -->
    <UserEditDialog
      v-model="editDialogVisible"
      :user="selectedUser"
      @updated="fetchUsers"
    />

    <!-- 用户属性管理对话框 -->
    <UserAttributesDialog
      v-model="attributesDialogVisible"
      :user="selectedUser"
      @updated="fetchUsers"
    />

    <!-- 用户关系管理对话框 -->
    <UserRelationsDialog
      v-model="relationsDialogVisible"
      :user="selectedUser"
    />

    <!-- 活动记录对话框 -->
    <!-- <UserActivitiesDialog
      v-model="activitiesDialogVisible"
      :user="selectedUser"
    /> -->
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, Refresh, Download, View as ViewIcon, Edit, MoreFilled, Setting, 
  Connection, Close, Check, Clock, ShoppingCart 
} from '@element-plus/icons-vue'
import { getUserList, toggleUserStatus, exportUsers, batchDeleteUsers } from '@/api/user'
import UserDetailDialog from './components/UserDetailDialog.vue'
import UserEditDialog from './components/UserEditDialog.vue'
import UserAttributesDialog from './components/UserAttributesDialog.vue'
import UserRelationsDialog from './components/UserRelationsDialog.vue'
// import UserActivitiesDialog from './components/UserActivitiesDialog.vue'
import { format } from 'date-fns'
import { useUserStore } from '@/stores/user'

export default {
  name: 'UserList',
  components: {
    UserDetailDialog,
    UserEditDialog,
    UserAttributesDialog,
    UserRelationsDialog,
    Search, Refresh, Download, ViewIcon, Edit, MoreFilled, Setting,
    Connection, Close, Check, Clock, ShoppingCart
    // UserActivitiesDialog
  },
  setup() {
    // 响应式数据
    const loading = ref(false)
    const userList = ref([])
    const total = ref(0)
    const selectedUsers = ref([])
    
    // 对话框状态
    const detailDialogVisible = ref(false)
    const editDialogVisible = ref(false)
    const attributesDialogVisible = ref(false)
    const relationsDialogVisible = ref(false)
    const activitiesDialogVisible = ref(false)
    
    const selectedUserId = ref(null)
    const selectedUser = ref(null)
    const isDeletingNoAvatarUsers = ref(false)

    // 搜索表单
    const searchForm = reactive({
      keyword: '',
      is_active: null
    })

    // 分页数据
    const pagination = reactive({
      page: 1,
      per_page: 10
    })

    const getAvatarUrl = (avatar) => {
      if (!avatar) {
        return 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'
      }
      if (avatar.startsWith('http')) {
        return avatar
      }
      // 假设你的后端图片服务地址是 'https://image.your-domain.com/'
      // 请根据你的实际情况修改这个基础URL
      return `https://dpcurdgwzmkg.sealosbja.site/${avatar}`
    }

    // 获取用户列表
    const fetchUsers = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.page,
          per_page: pagination.per_page,
          ...searchForm
        }
        
        console.log('Fetching users with params:', params)
        const response = await getUserList(params)
        console.log('API response:', response)
        
        userList.value = response.data.users.map(user => ({
          ...user,
          statusLoading: false
        }))
        total.value = response.data.total
      } catch (error) {
        console.error('Failed to fetch users:', error)
        ElMessage.error('获取用户列表失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      fetchUsers()
    }

    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        keyword: '',
        is_active: null
      })
      pagination.page = 1
      fetchUsers()
    }

    // 分页处理
    const handleSizeChange = (val) => {
      pagination.per_page = val
      pagination.page = 1
      fetchUsers()
    }

    const handleCurrentChange = (val) => {
      pagination.page = val
      fetchUsers()
    }

    // 选择处理
    const handleSelectionChange = (val) => {
      selectedUsers.value = val
    }

    // 状态切换
    const handleStatusChange = async (user) => {
      user.statusLoading = true
      try {
        await toggleUserStatus(user.id, { is_active: user.is_active })
        ElMessage.success(`用户${user.is_active ? '启用' : '禁用'}成功`)
      } catch (error) {
        user.is_active = !user.is_active // 恢复原状态
        ElMessage.error('状态修改失败：' + error.message)
      } finally {
        user.statusLoading = false
      }
    }

    // 操作处理
    const handleView = (user) => {
      selectedUserId.value = user.id
      detailDialogVisible.value = true
    }

    const handleEdit = (user) => {
      selectedUser.value = { ...user }
      editDialogVisible.value = true
    }

    const handleCommand = async (command, user) => {
      selectedUser.value = user
      
      switch (command) {
        case 'attributes':
          attributesDialogVisible.value = true
          break
        case 'relations':
          relationsDialogVisible.value = true
          break
        case 'activities':
          activitiesDialogVisible.value = true
          break
        case 'disable':
          await handleDisableUser(user)
          break
      }
    }

    const handleDisableUser = async (user) => {
      const action = user.is_active ? '禁用' : '启用'
      try {
        await ElMessageBox.confirm(
          `确定要${action}用户 "${user.nickname}" 吗？`,
          `${action}用户`,
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await toggleUserStatus(user.id, { is_active: !user.is_active })
        ElMessage.success(`${action}成功`)
        fetchUsers()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(`${action}失败：` + error.message)
        }
      }
    }

    // 导出
    const handleExport = () => {
      ElMessage.info('导出功能开发中...')
    }

    // 计算属性
    const activeUsersCount = computed(() => {
      return userList.value.filter(user => user.is_active).length
    })

    // 辅助函数
    const formatTime = (time) => {
      return time ? format(new Date(time), 'yyyy-MM-dd HH:mm:ss') : '-'
    }

    // 删除无头像用户
    const deleteNoAvatarUsers = async () => {
      try {
        await ElMessageBox.confirm('此操作将永久删除所有没有设置头像的用户，是否继续？', '警告', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'tech-messagebox',
        });

        isDeletingNoAvatarUsers.value = true;

        // 筛选出没有头像的用户ID
        const userIdsToDelete = userList.value
          .filter(user => !user.avatar_url)
          .map(user => user.id);

        if (userIdsToDelete.length === 0) {
          ElMessage.info({ message: '没有找到需要删除的无头像用户。', customClass: 'tech-message' });
          return;
        }
        
        // 调用批量删除接口
        const response = await batchDeleteUsers({ ids: userIdsToDelete });

        if (response.code === 200) {
          ElMessage.success({ message: `成功删除了 ${userIdsToDelete.length} 个无头像用户。`, customClass: 'tech-message' });
          fetchUsers(); // 刷新用户列表
        } else {
          // 如果API返回了错误信息，则显示它
          throw new Error(response.message || '删除失败，请稍后再试。');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除无头像用户失败:', error);
          const errorMessage = error instanceof Error ? error.message : '删除操作失败或已取消。';
          ElMessage.error({ message: errorMessage, customClass: 'tech-message' });
        }
      } finally {
        isDeletingNoAvatarUsers.value = false;
      }
    };

    // 挂载时获取数据
    onMounted(() => {
      console.log('UserList component mounted')
      fetchUsers()
    })

    return {
      loading,
      userList,
      total,
      selectedUsers,
      searchForm,
      pagination,
      detailDialogVisible,
      editDialogVisible,
      attributesDialogVisible,
      relationsDialogVisible,
      activitiesDialogVisible,
      selectedUserId,
      selectedUser,
      activeUsersCount,
      fetchUsers,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleStatusChange,
      handleView,
      handleEdit,
      handleCommand,
      handleExport,
      formatTime,
      getAvatarUrl,
      deleteNoAvatarUsers,
      isDeletingNoAvatarUsers
    }
  }
}
</script>

<style lang="scss" scoped>
.user-management {
  padding: 24px;
  min-height: 100vh;
  background: transparent;
  position: relative;
}

// 页面头部
.page-header {
  margin-bottom: 32px;
  animation: slideInUp 0.6s ease;
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    
    .header-left {
      .page-title {
        font-size: 32px;
        font-weight: 700;
        margin: 0 0 8px 0;
        line-height: 1.2;
      }
      
      .page-subtitle {
        color: var(--text-secondary);
        font-size: 16px;
        margin: 0;
        opacity: 0.8;
      }
    }
    
    .header-right {
      .user-stats {
        display: flex;
        gap: 24px;
        
        .stat-item {
          text-align: center;
          
          .stat-label {
            display: block;
            font-size: 12px;
            color: var(--text-secondary);
            margin-bottom: 4px;
          }
          
          .stat-value {
            font-size: 24px;
            font-weight: 700;
            color: var(--text-primary);
            
            &.success {
              color: var(--accent-green);
            }
          }
        }
      }
    }
  }
}

// 搜索区域
.search-section {
  margin-bottom: 32px;
  padding: 24px;
  animation: slideInUp 0.6s ease 0.1s both;
  
  .search-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .search-title {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);
      margin: 0;
    }
    
    .search-stats {
      .result-count {
        font-size: 14px;
        color: var(--text-secondary);
        background: rgba(102, 126, 234, 0.1);
        padding: 4px 12px;
        border-radius: 12px;
        border: 1px solid rgba(102, 126, 234, 0.3);
      }
    }
  }
  
  .search-form {
    .tech-form {
      :deep(.el-form-item__label) {
        color: var(--text-secondary);
        font-weight: 500;
      }
      
      .search-actions {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        
        .el-form-item__content {
          display: flex;
          gap: 12px;
        }
      }
    }
  }
}

// 表格区域
.table-section {
  padding: 24px;
  animation: slideInUp 0.6s ease 0.2s both;
  
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .table-title {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-primary);
      margin: 0;
    }
    
    .table-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .table-container {
    margin-bottom: 24px;
    
    // 表格内容样式
    .user-id {
      .id-badge {
        background: var(--primary-gradient);
        color: white;
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 600;
      }
    }
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .user-avatar {
        border: 2px solid var(--border-color);
        transition: all 0.3s ease;
        
        &:hover {
          border-color: var(--accent-purple);
          transform: scale(1.1);
        }
      }
      
      .user-details {
        .user-name {
          font-weight: 600;
          color: var(--text-primary);
          margin-bottom: 2px;
        }
        
        .user-phone {
          font-size: 12px;
          color: var(--text-secondary);
        }
      }
    }
    
    .gender-tag {
      display: flex;
      justify-content: center;
      
      .gender-icon {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
        font-size: 14px;
        
        &.male {
          background: rgba(79, 172, 254, 0.2);
          color: var(--accent-cyan);
        }
        
        &.female {
          background: rgba(240, 147, 251, 0.2);
          color: var(--accent-pink);
        }
        
        &.unknown {
          background: rgba(255, 255, 255, 0.1);
          color: var(--text-secondary);
        }
      }
    }
    
    .status-switch {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px;
      
      .status-label {
        font-size: 11px;
        color: var(--text-secondary);
      }
    }
    
    .orders-count {
      display: flex;
      align-items: center;
      gap: 6px;
      justify-content: center;
      
      .order-icon {
        color: var(--accent-green);
        font-size: 14px;
      }
      
      .count {
        font-weight: 600;
        color: var(--text-primary);
      }
    }
    
    .time-info {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 12px;
      
      .time-icon {
        color: var(--text-secondary);
      }
    }
    
    .action-buttons {
      display: flex;
      gap: 8px;
      align-items: center;
      
      .tech-btn {
        padding: 6px 12px;
        font-size: 12px;
        
        .el-icon {
          font-size: 12px;
        }
      }
      
      .action-dropdown {
        .tech-btn {
          padding: 6px 8px;
        }
      }
    }
  }
  
  .pagination-section {
    display: flex;
    justify-content: center;
    margin-top: 32px;
  }
}

// 状态点样式
.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
  
  &.status-success {
    background: var(--accent-green);
  }
  
  &.status-danger {
    background: #ff6b6b;
  }
}

// 响应式适配
@media (max-width: 768px) {
  .user-management {
    padding: 16px;
  }
  
  .page-header {
    .header-content {
      flex-direction: column;
      gap: 16px;
      
      .header-right {
        align-self: stretch;
        
        .user-stats {
          justify-content: space-around;
        }
      }
    }
  }
  
  .search-section,
  .table-section {
    padding: 16px;
  }
  
  .search-form {
    .el-row .el-col {
      margin-bottom: 16px;
    }
    
    .search-actions {
      justify-content: center;
      
      .el-form-item__content {
        flex-wrap: wrap;
        justify-content: center;
      }
    }
  }
  
  .table-container {
    overflow-x: auto;
    
    .user-info {
      min-width: 150px;
    }
    
    .action-buttons {
      flex-direction: column;
      gap: 4px;
      min-width: 80px;
      
      .tech-btn {
        width: 100%;
        font-size: 11px;
      }
    }
  }
}
</style> 